package gw.com.android.ui.chart;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.gwtsz.chart.output.utils.ChartConfig;
import com.gwtsz.chart.output.utils.GTTFormularContent;
import com.gwtsz.chart.output.utils.GTTFormularParam;
import com.gwtsz.gts2.hx.R;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import gw.com.android.app.AppMain;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.ui.BaseActivity;
import www.com.library.app.Logger;
import www.com.library.util.CommonUtils;
import www.com.library.util.DoubleConverter;
import www.com.library.view.NumberInput;
import www.com.library.view.RecycleViewDivider;
import www.com.library.view.TintTextView;

/**
 * Created by reeta.zou on 2016/10/24.
 *
 * 指标参数设置界面
 */
public class ChartSetActivity extends BaseActivity{
    @BindView(R.id.list_view)
    RecyclerView mListView;
    @BindView(R.id.parmas_right_list_view)
    LinearLayout mRightView;
    @BindView(R.id.parmas_empty)
    TextView emptyView;
    @BindView(R.id.save_parameters_view)
    LinearLayout btnLayout;

    /**图表用到各弹层中的数据处理类对象*/
    private ChartTypeData mChartTypeData;
    private DataAdapter mAdapter;
    private ArrayList<String> mFormularNameList;
    private GTTFormularContent mFormularContent;
    private String formularName = "BBI";
    private int mCurPositon = 0;
    private static String TAG=ChartSetActivity.class.getSimpleName();
    private static String METHOD="class="+TAG+" method=";

    @Override
    protected int getLayoutView() {
        return R.layout.activity_chart_set;
    }

    @Override
    protected void initLayoutView() {
        ButterKnife.bind(this);
        mTitleBar.setAppTitle(getString(R.string.chart_set_up_charts_index));
        //mTitleBar.setLeftResource( R.string.chart_switch_indicator_title);
        //mTitleBar.setLeftButtonVisible(true);
        // 设置布局管理器
        mListView.setLayoutManager(new LinearLayoutManager(this));
        mListView.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL));

    }

    public void setScreenOrien() {
        if(ChartConfig.instance().isScreenPort()){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }else{
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
    }

    @Override
    protected void initViewData() {
        if(null != getIntent()){
            formularName = getIntent().getStringExtra("mCurFormularName");
        }

        mChartTypeData = ChartTypeData.instance();
        getIndexListData();
        mAdapter = new DataAdapter(mCurPositon, this);
        mListView.setAdapter(mAdapter);
        addRightParmasView();
    }

    /**
     * 保存指标
     */
    @OnClick(R.id.btn_save_parameters)
    void saveParams(){
        Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName());
        if(CommonUtils.isFastDoubleClick()){
            return;
        }
        if(null != mFormularContent && mFormularContent.mParamList != null && mFormularContent.mParamList.size() > 0){
            for (GTTFormularParam mParam: mFormularContent.mParamList){
                if(DoubleConverter.isLT(mParam.mDefaultVal, mParam.mMin, 2) || DoubleConverter.isGT(mParam.mDefaultVal, mParam.mMax, 2)){
                    String error = "";
                    if ("BOLL".equals(mFormularContent.mName) && "p".equals(mParam.mName)){
                        error = AppMain.getAppString(R.string.chart_save_parameters_error_msg,DoubleConverter.toStringData(mParam.mMin,1),
                                DoubleConverter.toStringData(mParam.mMax,0));
                    }else{
                        error = AppMain.getAppString(R.string.chart_save_parameters_error_msg,DoubleConverter.toStringData(mParam.mMin,0),
                                DoubleConverter.toStringData(mParam.mMax,0));
                    }
                    showToastPopWindow(error);
                    return;
                }
            }
        }
        AppTerminal.instance().asyncSaveFormularContent(mFormularContent, 0);
        mFormularContent.setParamNum();
        showToastPopWindow(AppMain.getAppString(R.string.chart_save_parameters_success));
    }

    /**
     * 重置指标
     */
    @OnClick(R.id.btn_reset_default)
    void reset(){
        Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName());
        if(CommonUtils.isFastDoubleClick()){
            return;
        }
        mFormularContent.mParamList.clear();
        AppTerminal.instance().setFormularDefalut(mFormularContent.mName, mFormularContent,0);
        mFormularContent.setParamNum();
        mRightView.removeAllViews();
        addRightParmasView();
    }

    /**
     * 获取指标(主副图)所以指标
     */
    private void getIndexListData(){
        Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName());
        mFormularNameList = new ArrayList<>();
        String[] supIndicator = mChartTypeData.getChartSupIndicator();
        String[] infIndicator = mChartTypeData.getChartInfIndicator();
        for (int i = 0; i < supIndicator.length; i++) {
            mFormularNameList.add(supIndicator[i]);
        }
        for (int i = 0; i < infIndicator.length; i++) {
            mFormularNameList.add(infIndicator[i]);
        }

        //根据指标名获取指标所在位置
        int count = mFormularNameList.size();
        for(int i = 0 ; i < count; i++){
            if(formularName.equals(mFormularNameList.get(i))){
                mCurPositon = i;
                mFormularContent = new GTTFormularContent();
                AppTerminal.instance().getFormularContent(formularName,mFormularContent,0);
                mFormularContent.setParamNum();
                break;
            }
        }
    }

    private void addRightParmasView(){
        Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName());
        if(null == mFormularContent){
            emptyView.setVisibility(View.VISIBLE);
            btnLayout.setVisibility(View.GONE);
            return;
        }
        ArrayList<GTTFormularParam> parmas = mFormularContent.mParamList;
        if(parmas.size() == 0){
            emptyView.setVisibility(View.VISIBLE);
            btnLayout.setVisibility(View.GONE);
            return;
        }
        mFormularContent.print();
        for (int i = 0; i < mFormularContent.mParamNum; i++) {
            GTTFormularParam param = parmas.get(i);
            LinearLayout moreView = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.list_item_chart_index_params, null);
            ParamsView pv = new ParamsView();
            /**指标参数名称 */
            pv.index_param_name = (TextView) moreView.findViewById(R.id.index_param_name);
            /**指标参数值 */
            pv.index_param_number = (NumberInput) moreView.findViewById(R.id.index_param_number);
            pv.index_param_number.setDigits(7, 4, 2);
            /**指标选择器 */
            pv.seek_bar  = (SeekBar) moreView.findViewById(R.id.seek_bar);
            /**最小值 */
            pv.index_param_numbe_mins =  (TextView) moreView.findViewById(R.id.index_param_numbe_mins);
            /**最大值 */
            pv.index_param_numbe_max = (TextView) moreView.findViewById(R.id.index_param_numbe_max);
            pv.seek_bar.setTag(pv);
            pv.seek_bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                boolean isTracked = false;//标识滑块是否滑动过
                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    isTracked = false;
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {
                    isTracked = true;
                }

                @Override
                public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
                    if(isTracked){
                        ParamsView pv = (ParamsView) seekBar.getTag();
                        if(pv.index_param_numbe_mins.getText().toString().equals("0.1")){
                            if(progress == 0){
                                pv.index_param_number.setText("0.1");
                            }else{
                                pv.index_param_number.setText(progress+"");
                            }
                        }else{
                            int minValue = Integer.valueOf(pv.index_param_numbe_mins.getText().toString());
                            Logger.i("progress  == " + progress);
                            if(progress < minValue){
                                pv.index_param_number.setText((progress + minValue)+"");
                            }else{
                                pv.index_param_number.setText(progress+"");
                            }
                        }
                    }
                }
            });
            pv.index_param_name.setText(param.mName);
            pv.index_param_number.setText(DoubleConverter.toZeroOr2Decimal(param.mDefaultVal));
            pv.seek_bar.setMax((int)param.mMax);
            pv.seek_bar.setProgress((int)(Math.ceil(param.mDefaultVal)));
            if ("BOLL".equals(formularName) && "p".equals(param.mName)) {
                pv.index_param_numbe_mins.setText("0.1");
                param.mMin = DoubleConverter.toDoubleData("0.1");
                pv.index_param_number.setMin(0.1f);
            }else{
                pv.index_param_numbe_mins.setText((int)param.mMin+"");
                param.mMin = DoubleConverter.toDoubleData(String.valueOf(Math.round(param.mMin)));
                pv.index_param_number.setMin((float) param.mMin);
            }

            if("MA".equals(formularName)){
                pv.index_param_numbe_max.setText("300");
                param.mMax = DoubleConverter.toDoubleData("300");
                pv.seek_bar.setMax(300);
            }else{
                pv.index_param_numbe_max.setText((int)param.mMax+"");
                param.mMax = DoubleConverter.toDoubleData(String.valueOf(Math.round(param.mMax)));
                pv.seek_bar.setMax((int)param.mMax);
            }
            pv.index_param_number.addTextChangedListener(new EditTextMonitor(i, param, pv.seek_bar));
            mRightView.addView(moreView);
            emptyView.setVisibility(View.GONE);
            btnLayout.setVisibility(View.VISIBLE);
        }
    }

    private class EditTextMonitor implements TextWatcher {
        private int mValIdx;
        private SeekBar seek_bar;
        private GTTFormularParam param;

        public EditTextMonitor(int valIdx, GTTFormularParam param, SeekBar mseek_bar) {
            mValIdx = valIdx;
            seek_bar = mseek_bar;
            this.param = param;
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName()+",start="+start+",before="+before+",count="+count);
            if (mValIdx >= 0 && mValIdx < mFormularContent.mParamNum)
            {
                String mVals = s.toString();
                mVals =("".equals(mVals) == true ? "0":mVals);
                param.mDefaultVal = DoubleConverter.toDoubleData(mVals);
                int value = 0;
                if(mVals.length() > 0){
                    if(mVals.contains(".")){
                        double temp = Double.valueOf(mVals);
                        value  = (int)(Math.ceil(temp));
                    }else{
                        value = Integer.valueOf(mVals);
                    }
                }
                if(String.valueOf(param.mMin).equals("0.1")){
                    if(s.toString().equals("0.1")){
                        seek_bar.setProgress(0);
                    }else{
                        seek_bar.setProgress(value);
                    }
                }else{
                    int minValue = (int) param.mMin;
                    Logger.i("value  == " + value);
                    if(value <= minValue){
                        seek_bar.setProgress(value - minValue);
                    }else{
                        seek_bar.setProgress(value);
                    }
                }
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };

    public static class ParamsView{
        /**指标参数名称 */
        TextView index_param_name;
        /**指标参数值 */
        NumberInput index_param_number;
        /**指标选择器 */
        SeekBar seek_bar;
        /**最小值 */
        TextView index_param_numbe_mins;
        /**最大值 */
        TextView index_param_numbe_max;
    }

    /**
     * 列表适配器
     * @author reeta
     *
     */
    public class DataAdapter extends RecyclerView.Adapter{
        private LayoutInflater mInflater;
        public int mPosition = 0;

        public DataAdapter(int mPosition,Activity act) {
            mInflater = LayoutInflater.from(act);
            this.mPosition = mPosition;
        }

        public String getItem(int position) {
            if (position < 0 || position >= mFormularNameList.size())
                return null;
            return mFormularNameList.get(position);
        }

        public void refreshData(int mPosition){
            this.mPosition = mPosition;
            notifyDataSetChanged();
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = mInflater.inflate(R.layout.list_item_chart_index, parent,false);
            return new ItemView(itemView);
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            ItemView viewHold = (ItemView) holder;
            if (viewHold.mView != null) {
                viewHold.mView.setText(getItem(position));
                viewHold.mView.setTag(position);
                if(mPosition == position){
                    viewHold.mView.setSelected(true);
                }else{
                    viewHold.mView.setSelected(false);
                }
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getItemCount() {
            if(null != mFormularNameList){
                return mFormularNameList.size();
            }
            return 0;
        }

        class ItemView extends RecyclerView.ViewHolder{

            @BindView(R.id.item_title)
            TintTextView mView;

            public ItemView(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }

            @OnClick(R.id.item_layout)
            void onClick() {
                if(CommonUtils.isFastDoubleClick()){
                    return;
                }
                mCurPositon = (int) mView.getTag();
                refreshData(mCurPositon);
                mRightView.removeAllViews();
                formularName = getItem(mCurPositon);
                mFormularContent = new GTTFormularContent();
                AppTerminal.instance().getFormularContent(formularName,mFormularContent,0);
                mFormularContent.setParamNum();
                addRightParmasView();
            }
        }
    }
}
